package com.example.demo.interceptor;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyInterceptor implements HandlerInterceptor {

    protected static Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    private static String getHeader(HttpServletRequest request, String headName) {
        String value = request.getHeader(headName);
        return (StringUtils.isNotBlank(value) && !"unknown"
                .equalsIgnoreCase(value)) ? value : "";
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        /*String ipFromNginx = getHeader(request, "X-Real-IP");
        logger.info("ipFromNginx:" + ipFromNginx);
        logger.info("getRemoteAddr:" + request.getRemoteAddr());*/
        logger.debug("requestURI："+request.getRequestURI()+",IP:："+request.getRemoteAddr()+"Method:"+request.getMethod());
        // 只有返回true才会继续向下执行，返回false取消当前请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        logger.debug("用户请求地址："+request.getRequestURI()+",用户IP："+request.getRemoteAddr());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
//        logger.debug("用户请求的方法："+request.getRequestURI()+",用户的IP地址："+request.getRemoteAddr());
    }

}
